import {hostname} from "os"
import {BackendProcessBuilder} from "./backendProcess"
import {GameNames} from "./gameName";
import DouDiZhuLobby from "./match/doudizhu/centerlobby"
import Room from "./match/doudizhu/room"
import {BattleRoom} from "./match/doudizhu/TournamentRoom"
import config from "./utils/config"
import {logger} from "./utils/logger";


process.on('unhandledRejection', error => {
  console.error('unhandledRejection', error.stack)
})


const instance_id = process.env.INSTANCE_ID

if (!instance_id) {
  console.error('process.env.INSTANCE_ID can NOT be empty')
  process.exit(-1)
} else {
  logger.info('run with instance_id id', instance_id)
}


async function boot() {
  const cluster = `${hostname()}-${GameNames.doudizhu}-${instance_id}`

  const process = new BackendProcessBuilder()
    .withGameName(GameNames.doudizhu)
    .withClusterName(cluster)
    .connectToMongodb(config.get('database.url'))
    .connectRabbitMq('amqp://user:password@localhost:5672')
    .useRoomRecoverPolicy((json) => json)
    .useRecover(async (json, repository) => {
      if (json.roomType === BattleRoom.RoomType) {
        return BattleRoom.recover(json, repository)
      }

      return Room.recover(json, repository)
    })
    .useLobby(new DouDiZhuLobby())
    .build()

  await process.execute()
}


boot()
  .then(() => {
    logger.info('backend start with pid', process.pid)
  })
  .catch(error => {
    console.error(`boot backend ${GameNames.doudizhu} error`, error.stack)
  })
